//
//  SortViewController.m
//  HuaLang
//
//  Created by iking on 2017/11/20.
//  Copyright © 2017年 iking. All rights reserved.
//

#import "ClassifyViewController.h"
#import "LeftTableViewCell.h"
#import "ClassifyCollectionViewCell.h"
#import "GoodsListViewController.h"
#import "ClassifyTableViewCell.h"
#import "GoodsModel.h"
#import "GoodsDetailViewController.h"
#import "RightTableViewCell.h"
#import "RightGoodsTableViewCell.h"

@interface ClassifyViewController ()<UITableViewDelegate,UITableViewDataSource,RightTableViewCellDelegate,RightGoodsTableViewCellDelegate>

@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) UITableView *rightTableView;

@property (nonatomic, strong) NSMutableArray *firstTypeArray; // 栏目列表
@property (nonatomic, strong) NSMutableArray *goodsArray; // 商品列表

@property (nonatomic, assign) NSInteger selectIndex;
//@property (nonatomic, strong) NSString *firstType;
//@property (nonatomic, strong) NSString *secondType;

@end

@implementation ClassifyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = UIColorWhite;
    [self loadBaseTitleLable:@"商品分类"];
    self.leftBtn.hidden = YES;
    
    self.selectIndex = 0;
    
    [self.view addSubview:self.leftTableView];
    [self.view addSubview:self.rightTableView];
    
    [self getListData];
}
#pragma mark - 栏目列表
- (void)getListData
{
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/channel/channel.ashx?action=class&companyid=%@&channelid=105",kServerURL,companyId] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        self.firstTypeArray = [NSMutableArray array];
        if ([responseObject[@"status"] intValue] == 1) {
            NSArray *array = responseObject[@"list"];
            for (NSDictionary *dic in array) {
                [self.firstTypeArray addObject:dic];
            }
        }
        [self.leftTableView reloadData];
        NSDictionary *dic = self.firstTypeArray[self.selectIndex];
        NSLog(@"classDic:%@",dic);
        if ([dic[@"list"] isKindOfClass:[NSArray class]]) {
            [self.rightTableView reloadData];
            
        } else {
            // 没有二级
            [self getGoodsListWithClassid:dic[@"classid"]];
        }
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
        
    }];
}
#pragma mark - 获取商品
- (void)getGoodsListWithClassid:(NSString *)classid
{
    [MBProgressHUD showMessage:nil toView:self.view];
    [TFNetworking getWithURLString:[NSString stringWithFormat:@"%@/api/json/content/content.ashx?action=list&companyid=%@&channelid=105&pagesize=100000&pageindex=1&classid=%@",kServerURL,companyId,classid] parameters:nil success:^(id responseObject) {
        [MBProgressHUD hideHUDForView:self.view];
        self.goodsArray = [NSMutableArray array];
        if ([responseObject[@"status"] intValue] == 1) {
            self.goodsArray = [GoodsModel mj_objectArrayWithKeyValuesArray:responseObject[@"list"]];
        }
        [self.rightTableView reloadData];
        
    } failure:^(NSError *error) {
        [TFHUD addRemindHUD:self.view message:@"网络不给力..."];
    }];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = NO;
}
#pragma mark - tableView delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _leftTableView) {
        return 1;
    } else {
        NSDictionary *dic = _firstTypeArray[self.selectIndex];
        if ([dic[@"list"] isKindOfClass:[NSArray class]]) {
            NSArray *array = dic[@"list"];
            NSInteger countNum = 0;
            for (NSDictionary *dic in array) {
                countNum = countNum + [dic[@"classCount"] intValue];
            }
            if (countNum == 0) {
                return 2;
            } else {
                return array.count+1;
            }
        } else {
            return 2;
        }
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _leftTableView) {
        return _firstTypeArray.count;
    } else {
        return 1;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _leftTableView) {
        LeftTableViewCell *cell = [[LeftTableViewCell alloc] init];
        cell.contentView.backgroundColor = UIColorFromRGB(0xececec);
        NSDictionary *dic = _firstTypeArray[indexPath.row];
        cell.textLB.text = dic[@"className"];
        if (indexPath.row == self.selectIndex) {
            cell.contentView.backgroundColor = UIColorWhite;
            cell.textLB.textColor = UIColorFromRGB(0x000000);
            cell.leftSegmentV.backgroundColor = navBarColor;
        }
        cell.selectionStyle = NO;
        return cell;
    } else {
        if (indexPath.section == 0) {
            // 广告图
            UITableViewCell *cell = [[UITableViewCell alloc] init];
            
            NSDictionary *dic = _firstTypeArray[self.selectIndex];
            if ([dic[@"mobileclassImages"] length] != 0) {
                UIImageView *topImg = [[UIImageView alloc] init];
                //            topImg.image = UIImageNamed(@"1000-6");
                [cell.contentView addSubview:topImg];
                [topImg mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.width.equalTo(@(kScreenWidth-rateWidth(200)));
                    make.top.equalTo(cell.contentView).offset(rateHeight(10));
                    make.left.equalTo(cell.contentView).offset(rateWidth(10));
                    make.height.equalTo(@((kScreenWidth-rateWidth(200))/2));
                }];
                [topImg sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http:%@",dic[@"mobileclassImages"]]] placeholderImage:UIImageNamed(@"1000-6")];
            }
            
            cell.selectionStyle = NO;
            return cell;
        } else {
            NSDictionary *dic = _firstTypeArray[self.selectIndex];
            if ([dic[@"list"] isKindOfClass:[NSArray class]]) {
                NSArray *array = dic[@"list"];
                NSInteger countNum = 0;
                for (NSDictionary *dic in array) {
                    countNum = countNum + [dic[@"classCount"] intValue];
                }
                RightTableViewCell *cell = [[RightTableViewCell alloc] init];
                // 赋值
                if (countNum == 0) {
                    
                    cell.itemArray = [NSArray arrayWithArray:array];
                    cell.delegate = self;
                    
                } else {
                    NSDictionary *subDic = array[indexPath.section-1];
                    if ([subDic[@"list"] isKindOfClass:[NSArray class]]) {
                        NSArray *subArray = subDic[@"list"];
                        
                        cell.itemArray = [NSArray arrayWithArray:subArray];
                        cell.delegate = self;
                    }
                }
                cell.selectionStyle = NO;
                return cell;
                
            } else {
                RightGoodsTableViewCell *cell = [[RightGoodsTableViewCell alloc] init];
                cell.delegate = self;
                // 赋值
                if (self.goodsArray.count != 0) {
                    cell.itemArray = self.goodsArray;
                    [cell.collectionView mas_remakeConstraints:^(MASConstraintMaker *make) {
                        make.height.equalTo(@(rateHeight(300)*(int)ceil(cell.itemArray.count / 2.0)));
                        make.width.equalTo(@(kScreenWidth-rateWidth(180)));
                        make.top.equalTo(cell.contentView);
                        make.left.equalTo(cell.contentView);
                    }];
                }
                
                cell.selectionStyle = NO;
                return cell;
            }
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _leftTableView) {
        return rateHeight(100);
    } else {
        if (indexPath.section == 0) {
            NSDictionary *dic = _firstTypeArray[self.selectIndex];
            if ([dic[@"mobileclassImages"] length] != 0) {
                return rateHeight(20)+(kScreenWidth-rateWidth(200))/2;
            } else {
                return 0.01;
            }
            
        } else {
            NSDictionary *dic = _firstTypeArray[self.selectIndex];
            if ([dic[@"list"] isKindOfClass:[NSArray class]]) {
                NSArray *array = dic[@"list"];
                NSDictionary *subDic = array[indexPath.section-1];
                if ([subDic[@"list"] isKindOfClass:[NSArray class]]) {
                    NSArray *subArray = subDic[@"list"];
                    return rateHeight(160)*(int)ceil(subArray.count / 3.0);
                } else {
                    return rateHeight(160);
                }
                
            } else {
                return rateWidth(300)*(int)ceil(self.goodsArray.count / 2.0);
            }
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (tableView == _rightTableView) {
        if (section != 0) {
            NSDictionary *dic = _firstTypeArray[self.selectIndex];
            if ([dic[@"list"] isKindOfClass:[NSArray class]]) {
                NSArray *array = dic[@"list"];
                
                NSInteger countNum = 0;
                for (NSDictionary *dic in array) {
                    countNum = countNum + [dic[@"classCount"] intValue];
                }
                if (countNum != 0) {
                    return rateHeight(70);
                } else {
                    return rateHeight(10);
                }
            } else {
                return 0.01;
            }
            
        } else {
            return rateHeight(10);
        }
    } else {
        return 0.01;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (tableView == _rightTableView) {
        if (section != 0) {
            UIView *bgV = [[UIView alloc] init];
            bgV.backgroundColor = UIColorWhite;
            
            UILabel *label = [UILabel labelWithText:@"" textColor:UIColorFromRGB(0x333333) fontSize:13];
            [label sizeToFit];
            [bgV addSubview:label];
            [label mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(bgV);
                make.left.equalTo(bgV).offset(rateWidth(10));
            }];
            // 赋值
            NSDictionary *dic = _firstTypeArray[self.selectIndex];
            if ([dic[@"list"] isKindOfClass:[NSArray class]]) {
                NSArray *array = dic[@"list"];
                
                NSInteger countNum = 0;
                for (NSDictionary *dic in array) {
                    countNum = countNum + [dic[@"classCount"] intValue];
                }
                if (countNum != 0) {
                    NSDictionary *subDic = array[section-1];
                    if (subDic[@"className"]) {
                        label.text = subDic[@"className"];
                    }
                }
                
            }
            return bgV;
        } else {
            return nil;
        }
        
    } else {
        return nil;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _leftTableView) {
        self.selectIndex = indexPath.row;
        [_leftTableView reloadData];
        LeftTableViewCell *cell = (LeftTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        cell.contentView.backgroundColor = UIColorWhite;
        cell.textLB.textColor = UIColorFromRGB(0x000000);
        cell.leftSegmentV.backgroundColor = navBarColor;
        
        NSDictionary *dic = _firstTypeArray[self.selectIndex];
        NSLog(@"classDic:%@",dic);
        if ([dic[@"list"] isKindOfClass:[NSArray class]]) {
            [self.rightTableView reloadData];
            
        } else {
            // 没有二级
            [self getGoodsListWithClassid:dic[@"classid"]];
        }
    }
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _leftTableView) {
        LeftTableViewCell *cell = (LeftTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
        //        self.firstType = self.firstTypeArray[indexPath.row];
        cell.contentView.backgroundColor = UIColorFromRGB(0xececec);
        cell.textLB.textColor = UIColorFromRGB(0x6d6d6d);
        cell.leftSegmentV.backgroundColor = kClearColor;
    }
}
#pragma mark - collectionView cell 点击
- (void)sendClassDic:(NSDictionary *)dic
{
    GoodsListViewController *secondSortVC = [[GoodsListViewController alloc] init];
    secondSortVC.classid = dic[@"classid"];
    [self.navigationController pushViewController:secondSortVC animated:YES];
}
#pragma mark - collectionView 商品 点击
- (void)sendGoodsModel:(GoodsModel *)model
{
    GoodsDetailViewController *goodsDetailVC = [[GoodsDetailViewController alloc] init];
    goodsDetailVC.contentId = model.id;
    [self.navigationController pushViewController:goodsDetailVC animated:YES];
}
- (UITableView *)leftTableView
{
    if (!_leftTableView) {
        _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, rateWidth(180), kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight-49) style:(UITableViewStyleGrouped)];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.backgroundColor = UIColorFromRGB(0xececec);
        _leftTableView.separatorStyle = NO;
        _leftTableView.estimatedRowHeight = 0;
        _leftTableView.estimatedSectionFooterHeight = 0;
        _leftTableView.estimatedSectionHeaderHeight = 0;
    }
    return _leftTableView;
}
- (UITableView *)rightTableView
{
    if (!_rightTableView) {
        _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(rateWidth(180), SafeAreaTopHeight, kScreenWidth-rateWidth(180), kScreenHeight-SafeAreaBottomHeight-SafeAreaTopHeight-49) style:(UITableViewStyleGrouped)];
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
        _rightTableView.backgroundColor = UIColorWhite;
        _rightTableView.separatorStyle = NO;
        _rightTableView.estimatedRowHeight = 0;
        _rightTableView.estimatedSectionFooterHeight = 0;
        _rightTableView.estimatedSectionHeaderHeight = 0;
    }
    return _rightTableView;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
